﻿using System.CodeDom.Compiler;
using System.Text;
using Microsoft.CSharp;

namespace PmfWeb.Core.Dynamic
{
    ///<summary>
    /// 动态执行C#代码（从文件或从字符串）
    ///</summary>
    public class DynamicExecute
    {
        ///<summary>
        ///</summary>
        public DynamicExecute()
        {
            
        }
        ///<summary>
        ///</summary>
        ///<param name="filename"></param>
        ///<returns></returns>
        public string Compiler(string filename)
        {
            StringBuilder outResult = new StringBuilder("");
            CSharpCodeProvider provider = new CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("System.dll");

            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;

            CompilerResults results = compiler.CompileAssemblyFromFile(parameters, filename);
            
            if(results.Errors.HasErrors)
            {
                outResult.Append("编译错误");
                foreach (CompilerError error in results.Errors)
                {
                    outResult.AppendLine(error.ErrorText);
                }
            }
            return outResult.ToString();
        } 
    }
}
